#pragma once

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>

class Command
{
private:
    bool IsSafe(const std::string &cmd)
    {
        for(auto& c : _white_list)
        {
            if(cmd == c)
            {
                return true;
            }
        }
        return false;
    }

public:
    Command()
    {
        _white_list.push_back("ls -a -l");
        _white_list.push_back("ll");
        _white_list.push_back("la");
        _white_list.push_back("cat test.txt");
        _white_list.push_back("touch touch.txt");
        _white_list.push_back("pwd");
        _white_list.push_back("tree");
        _white_list.push_back("whoami");
    }
    std::string Exec(const std::string &cmd)
    {
        if(!IsSafe(cmd))
        {
            return "command error";
        }
        std::string ret;
        FILE *fp = popen(cmd.c_str(), "r"); // 以只读的方式打开
        if (fp == nullptr)
        {
            return cmd + "exec error";
        }
        else
        {
            char buffer[1024];
            while (fgets(buffer, sizeof(buffer), fp) != nullptr) // 将fp中的内容读取到bufer中
            {
                ret += buffer;
            }
            pclose(fp);
        }
        return ret;
    }
    ~Command() {}

private:
    std::vector<std::string> _white_list; // 命令白名单
};